

import threading
import time
from get_config import *

if 0:
    import HslCommunication
    from HslCommunication import SoftBasic, MelsecMcNet, MelsecMcAsciiNet, MelsecA1ENet, SiemensS7Net, SiemensPLCS, \
        SiemensFetchWriteNet, OmronFinsNet, ModbusTcpNet, OperateResult, NetSimplifyClient
else:
    from midea_common.mcplc.mcplc_class import McPlc as MelsecMcNet

#拍照触发
#位置偏差
#D2120为偏差数值，为当前物料位置相对模板向前（-）或向后偏（+）移量，32位浮点数。
# D30=1  NG  D30=2,复位
melsecr = MelsecMcNet(config['plc_ip'], port=8080)  # 读
melsecw = MelsecMcNet(config['plc_ip'], port=8090)  # 写

def plc_reopen():
    global melsecr
    global melsecw
    if melsecr is None:
        melsecr = MelsecMcNet(config['plc_ip'], port=8080)  # 读
    if melsecw is None:
        melsecw = MelsecMcNet(config['plc_ip'], port=8090)  # 写

def plc_close():
    global melsecr
    global melsecw
    if melsecr is not None:
        melsecr.CloseSocket()
        melsecr = None

    if melsecw is not None:
        melsecw.CloseSocket()
        melsecw = None


def plc_write16(t, x):
    #plc_reopen()
    melsecw.WriteInt16(t, x)

def plc_read16(t):
    for i in range(100):
        code = melsecr.ReadInt16(t)
        if code is not None:
            return code
        else:
            melsecr.reopen()

    #if code is None:
    return code

# 读编码器
def plc_get_code():
    #检测结果
    t = 'D100'
    code = plc_read16(t)
    # print(code,'编码器')
    #melsecw.ReadInt16(t, 0)
    if code is not None:
        if code >= 60530:
            return None
    return code

def plc_obj_is_in():
    #检测结果
    t = 'D60' #上升沿
    b = melsecr.ReadInt16(t)

    if b is not None and b>0:
        print('上升', b)
        time.sleep(0.2)
        melsecw.WriteInt16(t, 0)
        #print(b)
    return b

def plc_obj_is_out():
    #检测结果
    t = 'D62'  #下降沿
    b = melsecr.ReadInt16(t)
    if b is not None and b>0:
        time.sleep(0.2)
        melsecw.WriteInt16(t, 0)
        #print(b)
    return b

def plc_set_ng(end):
    if end:
        plc_write16('D30', 1)
    else:
        plc_write16('D30', 2)

def plc_obj_is_in():
    #检测结果
    t = 'D60' #上升沿
    b = plc_read16(t)

    if b is not None and b>0:
        print('上升', b)
        time.sleep(0.2)
        plc_write16(t, 0)
        #print(b)
    return b

def plc_obj_is_out():
    #检测结果
    t = 'D62'  #下降沿
    b = plc_read16(t)
    if b is not None and b>0:
        time.sleep(0.2)
        plc_write16(t, 0)
        #print(b)
    return b

def plc_in_saoma():
    t = 'D32'  #下降沿
    b = plc_read16(t)
    return b

def plc_set_ng(end):
    if end:
        plc_write16('D30', 1)
    else:
        plc_write16('D30', 2)

pre_live_time = time.time()
def plc_live():
    t = time.time()
    global pre_live_time
    tt = t-pre_live_time
    if tt>4:
        plc_write16('D31', 1)
        pre_live_time = t
